package com.nado.iims2.blog.action.notice;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.nado.extensions.pagination.PaginationInfo;
import com.nado.iims2.blog.bo.notice.NoticeBO;
import com.nado.iims2.blog.model.notice.Notice;
import com.nado.iims2.blog.util.CommonUtil;

/**
 * Handles requests for the application notice page.
 */
@Controller
public class NoticeController {
	/** The logger. */
	private static final Logger logger = LoggerFactory.getLogger(NoticeController.class);
	
	@Autowired
	private NoticeBO noticeBO = null;
	
	@RequestMapping(value = "/notice/notice", method = RequestMethod.GET)
	public String noticeList(HttpServletRequest request, Model model) {
		int page = NumberUtils.toInt(request.getParameter("page"), 1);
		List<Notice> noticeList = new ArrayList<Notice>();
		PaginationInfo paginationInfo = null;
		
		int count = noticeBO.getNoticeListCount();
		paginationInfo = new PaginationInfo("default", request, count);
		noticeList = noticeBO.getNoticeList(CommonUtil.calcOffset(page, paginationInfo.getPageSize()), paginationInfo.getPageSize());
		
		model.addAttribute("noticeCount", count);
		model.addAttribute("noticeList", noticeList);
		model.addAttribute("paginate", paginationInfo);
		
		return "/notice/noticeList";
	}
	
	@RequestMapping(value = "/notice/form", method = RequestMethod.GET)
	public String noticeForm(Model model) {
		Notice notice = new Notice();
		model.addAttribute(notice);
		return "/notice/noticeForm";
	}
	
	
	@RequestMapping(value = "/notice/write", method = RequestMethod.POST)
	public String write(@ModelAttribute Notice notice) {
		logger.info("notice write, user id is " + notice.getUserId());
		
		notice.setUserId("SYSTEM");
		
		if(noticeBO.writeNotice(notice) < 0) {
			return "redirect:/notice/form";
		}
		return "redirect:/notice/notice";
	}
}
